package com.uenpay.im.broadcastreceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.qyx.android.database.DBTalkMsgColumns;
import com.qyx.android.database.FriendDB;
import com.qyx.android.database.GroupTalkDbManager;
import com.qyx.android.database.TalkMsgManager;
import com.qyx.android.entity.FriendEntity;
import com.qyx.android.entity.GroupTalkEntity;
import com.qyx.android.message.type.MsgContentType;
import com.qyx.android.message.type.MsgStatusType;
import com.qyx.android.message.type.MsgType;
import com.qyx.android.message.type.PacketType;
import com.qyx.android.protocol.QyxMsg;
import com.uenpay.im.BroadcastAction;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.PushServiceConn;
import com.uenpay.im.ui.old.activity.SignInOnOtherDeviceDialog;
import com.uenpay.im.ui.old.activity.chat.manage.ChatItemDataManager;
import com.uenpay.im.configuration.ShareData;
import com.uenpay.im.entities.chatbean.MsgCancelCallVideoModel;
import com.uenpay.im.entities.chatbean.MsgCradModel;
import com.uenpay.im.entities.chatbean.MsgRefuseVideoChatModel;
import com.uenpay.im.service.MsgContentType2Name;
import com.qyx.videochat.util.VideoChatResultType;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.MessageFormat;
import java.util.ArrayList;

/**
 * 广播管理
 *
 * @author SL
 * @copyRight http://www.qiyunxin.com
 */
public class PushMsgReceiver extends BroadcastReceiver {

    private static final String TAG = "PushMsgReceiver";
    private Context mContext;
    private PushMsgReceiverHandle mPushMsgReceiverHandle = null;
    private TalkMsgManager talkMsgManager = new TalkMsgManager();

    @Override
    public void onReceive(Context context, Intent intent) {
        mContext = context;
        mPushMsgReceiverHandle = new PushMsgReceiverHandle(mContext);
        if (intent.getAction().equals(BroadcastAction.ACTION_PUSH_MSG_RECIVE)) {
            Bundle bundle = intent.getExtras();
            ArrayList<QyxMsg> arrayList = bundle.getParcelableArrayList("message");
            if (arrayList.size() == 1) {
                // TODO 在线消息
                operRecvMsg(arrayList.get(0), bundle.getBoolean("is_last_msg", true));
            } else {
                // TODO 离线消息
                operOffLineMsgs(arrayList, bundle.getBoolean("is_last_msg", true));
            }

        } else if (intent.getAction().equals(BroadcastAction.ACTION_FRIENDS_REQUEST)) {
            Bundle bundle = intent.getExtras();
            QyxMsg message = bundle.getParcelable("message");
            if (message != null) {
                mPushMsgReceiverHandle.showNotification(message.sessionModel.getSessionId() + "", 1, message.from_cust_name,
                        message.content, message, 0, 0);
            }
        } else if (intent.getAction().equals(BroadcastAction.ACTION_AUTH_EXPIRES)) {
            PushServiceConn.getInstance(mContext).stopChatService();
            /** 认证失败,重新登陆 **/
            Intent intent1 = new Intent(mContext, SignInOnOtherDeviceDialog.class);
            intent1.putExtra("type", MsgStatusType.SIGN_IN_OTHER_DEVICE);
            intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(intent1);
            return;
        }
        // else if (intent.getAction().equals(
        // BroadcastAction.ACTION_CANCEL_ADD_OFF_LINE_VIDEO_CHAT)) {
        // /** 添加离线视频请求消息通知 **/
        // Bundle bundle = intent.getExtras();
        // QyxMsg message = bundle.getParcelable("message");
        // mVideoChatOffLineMsgManager.addOffLineVideoChatMsg(message);
        // } else if (intent.getAction().equals(
        // BroadcastAction.ACTION_CANCEL_REMOVE_OFF_LINE_VIDEO_CHAT)) {
        // String msg_no = intent.getStringExtra("msg_no");
        // mVideoChatOffLineMsgManager.removeOffLineVideoChatMsg(msg_no);
        // } else if (intent.getAction()
        // .equals(BroadcastAction.ACTION_CONN_STAUTS)) {
        // mVideoChatOffLineMsgManager.checkOnLineVideoChatMsg();
        // }

    }

    /**
     * 处理离线消息
     *
     * @param arrayList
     */
    private void operOffLineMsgs(ArrayList<QyxMsg> arrayList, boolean is_last_msg) {
        if (arrayList.get(0).sessionModel.getSessionId() == 0) {
            for (int i = 0, size = arrayList.size(); i < size; i++) {
                operRecvMsg(arrayList.get(i), true);
            }
        } else {
            // TODO 其他类型的会话
            showNotification(arrayList, is_last_msg, arrayList.size());
        }
    }

    /**
     * 解析收到的消息
     *
     * @param message 消息对象
     */
    public void operRecvMsg(QyxMsg message, boolean is_last_msg) {
        if (message.msg_type.equals(MsgType.MSG_KICKED + "")) {
            PushServiceConn.getInstance(mContext).stopChatService();
            Intent intent = new Intent(mContext, SignInOnOtherDeviceDialog.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(intent);
            return;
        }

        if (message.msg_content_type == MsgContentType.REQUEST_VIDEO_CHAT) {
            mPushMsgReceiverHandle.answerVideoChat(message);
        } else if (message.msg_content_type == MsgContentType.REFUSE_VIDEO_CHAT
                || message.msg_content_type == MsgContentType.BUSY_VIDEO_CHAT) {
            /** 拒绝视频通话 **/
            // TODO
            Intent intent = new Intent(BroadcastAction.ACTION_REFUSE_VIDEO_CHAT);
            intent.putExtra("msg_no", message.content);
            if (message.msg_content_type == MsgContentType.BUSY_VIDEO_CHAT) {
                intent.putExtra("video_chat_result_type", VideoChatResultType.VideoChatResultTypeBusy);
            } else if (message.msg_content_type == MsgContentType.REFUSE_VIDEO_CHAT) {
                intent.putExtra("video_chat_result_type", VideoChatResultType.VideoChatResultTypeRefuse);
                MsgRefuseVideoChatModel msgRefuseVideoChatModel = (MsgRefuseVideoChatModel) message.baseContentModel;
                if (msgRefuseVideoChatModel != null) {
                    message.content = msgRefuseVideoChatModel.getRefuseVideoChatMsgNo();
                }
            }
            mContext.sendBroadcast(intent);
            String content_json = message.content_json;
            if (!TextUtils.isEmpty(content_json)) {
                JSONObject jsonObject;
                try {
                    jsonObject = new JSONObject(content_json);
                    if (jsonObject.has("video_chat_result")) {
                        jsonObject.remove("video_chat_result");
                    }
                    if (message.msg_content_type == MsgContentType.BUSY_VIDEO_CHAT) {
                        jsonObject.put("video_chat_result", VideoChatResultType.VideoChatResultTypeBusy);
                    } else if (message.msg_content_type == MsgContentType.REFUSE_VIDEO_CHAT) {
                        jsonObject.put("video_chat_result", VideoChatResultType.VideoChatResultTypeRefuse);
                    }
                    /** 更改数据库 **/
                    talkMsgManager.updateFieldMsgByMsgNo(DBTalkMsgColumns.CONTENT_JSON, jsonObject.toString(), message.content);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            return;
        } else if (message.msg_content_type == MsgContentType.CANCEL_CALL_VIDEO_CHAT) {
            MsgCancelCallVideoModel msgCancelCallVideoModel = (MsgCancelCallVideoModel) message.baseContentModel;
            if (msgCancelCallVideoModel != null) {
                Intent intent = new Intent(BroadcastAction.ACTION_CANCEL_CALL_VIDEO_CHAT);
                intent.putExtra("msg_no", msgCancelCallVideoModel.getCancelCallVideoMsgNo());
                String content_json = message.content_json;
                if (!TextUtils.isEmpty(content_json)) {
                    try {
                        JSONObject jsonObject = new JSONObject(content_json);
                        if (jsonObject.has("video_chat_result")) {
                            jsonObject.remove("video_chat_result");
                        }
                        jsonObject.put("video_chat_result", VideoChatResultType.VideoChatResultTypeCancelCall);
                        /** 更改数据库 **/
                        talkMsgManager.updateFieldMsgByMsgNo(DBTalkMsgColumns.CONTENT_JSON, jsonObject.toString(),
                                msgCancelCallVideoModel.getCancelCallVideoMsgNo());
                        intent.putExtra("content_json", jsonObject.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                // TODO
                mContext.sendBroadcast(intent);
                return;
                // talkMsgManager.updateFieldMsgByMsgNo(
                // DBTalkMsgColumns.VIDEO_CHAT_RESULT,
                // VideoChatResultType.VideoChatResultTypeCancelCall + "",
                // msgCancelCallVideoModel.getCancelCallVideoMsgNo());
            }

        } else if (message.msg_content_type == MsgContentType.DYNAMIC_NEW_DYNAMIC_PUBLISH) {
            mPushMsgReceiverHandle.receiveDynamicNewPublish(message);
            return;
        } else if (message.msg_content_type == MsgContentType.DYNAMIC_NEW_REPLY) {
            mPushMsgReceiverHandle.receiveDynamicNewReply(message);
            return;
        } else if (message.msg_content_type == MsgContentType.DELETE_FRIEND) {
            mPushMsgReceiverHandle.receiveDeleteFriend(message);
            return;
        } else if (message.msg_content_type == MsgContentType.REVOKE_MSG) {
            mPushMsgReceiverHandle.receiveWithdrawMsg(message);
            return;
        } else if (message.msg_content_type == MsgContentType.PHOTO_UPDATE
                || message.msg_content_type == MsgContentType.GROUP_TALK_PHOTO_UPDATE) {
            // 头像更新
            mPushMsgReceiverHandle.receivePhotoUpdate(message, message.msg_content_type);
            return;
        } else if (message.msg_content_type == MsgContentType.UPDATE_NICK_NAME) {
            // TODO 修改昵称
            IMApplication.getAppContext().sendBroadcast(new Intent(BroadcastAction.ACTION_REFRESH_FRIEND_NAME));
            return;
        }
        ArrayList<QyxMsg> arrayList = new ArrayList<QyxMsg>();
        arrayList.add(message);
        showNotification(arrayList, is_last_msg, 1);
    }

    private void showNotification(ArrayList<QyxMsg> arrayList, boolean is_last_msg, int msgCount) {
        boolean is_cur_chat = false;
        boolean is_read = false;
        IMApplication.IS_REFRESH_TOP_MSG = true;
        if ((arrayList.get(0).from_cust_id + "").equals(IMApplication.getCustId())) {
            is_read = true;
        }

        is_cur_chat = mPushMsgReceiverHandle.isCurrentChat(arrayList.get(0));
        if (is_cur_chat) {
            Bundle bundle = new Bundle();
            // bundle.putParcelable("message", messages);
            bundle.putParcelableArrayList("message", arrayList);
            Intent intent = new Intent();
            intent.setAction(BroadcastAction.ACTION_MSG_RECIVE);
            intent.putExtras(bundle);
            mContext.sendBroadcast(intent);
        }

        if (IMApplication.PAGE.PAGE_TALK == ShareData.getInstance().getCurPage()) {
            if (is_last_msg) {
                Log.d(TAG, "sendBroadcast TAKEING_MSG_TOP_MSG");
                Bundle bundle = new Bundle();
                // bundle.putParcelable("message", messages);
                bundle.putParcelableArrayList("message", arrayList);
                Intent intent = new Intent();
                intent.setAction(BroadcastAction.TAKEING_MSG_TOP_MSG);
                intent.putExtras(bundle);
                mContext.sendBroadcast(intent);
            }
        } else {
            IMApplication.IS_REFRESH_TOP_MSG = true;
        }

        int unread_msg_count = IMApplication.config.getUnreadChatMsgCount();
        boolean is_add_total = true;
        if (arrayList.get(0).sessionModel.getSessionType() == PacketType.GROUP) {
            GroupTalkDbManager groupTalkDbManager = new GroupTalkDbManager();
            GroupTalkEntity groupTalk = groupTalkDbManager.queryGroupByGroupId(Long.valueOf(arrayList.get(0).sessionModel.getSessionId()));
            if (groupTalk.is_remind == 1) {
                is_add_total = false;
            }
        } else {
            FriendEntity entity = FriendDB.getFriend(arrayList.get(0).from_cust_id + "");
            if (entity != null) {
                if (entity.is_remind == 1) {
                    is_add_total = false;
                }
            }
        }
        if (is_add_total) {
            unread_msg_count += msgCount;
            IMApplication.config.setUnreadChatMsgCount(unread_msg_count);
        }

        // int unread_msg_count = 0;
        // if (!is_cur_chat) {
        // unread_msg_count = IMApplication.config.getUnreadChatMsgCount();
        // unread_msg_count++;
        // IMApplication.config.setUnreadChatMsgCount(unread_msg_count);
        // }

        if (!is_cur_chat && is_last_msg) {
            Intent intent = new Intent(BroadcastAction.MSG_ACTION);
            intent.putExtra("count", unread_msg_count);
            intent.putExtra("info", "add");
            mContext.sendBroadcast(intent);
        }

        boolean is_notify = false;
        boolean is_at = false;
        /**
         * 检查@信息
         */
        if (arrayList.get(0).sessionModel.getSessionType() == PacketType.GROUP
                && (arrayList.get(0).content.indexOf("@" + IMApplication.getCustName()) != -1 || (arrayList.get(0).msg_content_type == MsgContentType.ALTER_GROUP_TALK_INTRO && arrayList
                .get(0).from_cust_id != Long.valueOf(IMApplication.getCustId())))) {
            is_at = true;
            mPushMsgReceiverHandle.receivedAtMsg(arrayList.get(0));
        }

        if (!is_read && !(is_cur_chat && IMApplication.PAGE.PAGE_TALK_DETAIL == ShareData.getInstance().getCurPage())
                && IMApplication.PAGE.PAGE_TALK != ShareData.getInstance().getCurPage()) {
            is_notify = true;
        }

        if ((is_notify || is_at) && is_last_msg) {
            String content = MsgContentType2Name.GetMsgContentTypeName(arrayList.get(0).msg_content_type);
            /** 优先显示备注名 **/
            String from_cust_name = IMApplication.config.getFriendsRemarkName(arrayList.get(0).from_cust_id + "");
            if (TextUtils.isEmpty(from_cust_name)) {
                from_cust_name = arrayList.get(0).from_cust_name;
            }
            if (TextUtils.isEmpty(content) || arrayList.get(0).msg_content_type == MsgContentType.TEXT) {
                content = ChatItemDataManager.getSystemContent(arrayList.get(0).content_json, arrayList.get(0).content);
            }
            if (arrayList.get(0).msg_content_type == MsgContentType.BUSINESS_CRAD) {
                MsgCradModel msgCradModel = (MsgCradModel) arrayList.get(0).baseContentModel;
                if (msgCradModel != null) {
                    content = MessageFormat.format(IMApplication.getAppContext().getResources().getString(R.string.crad_msg_notice),
                            arrayList.get(0).from_cust_name, msgCradModel.getCustName());
                }
            }
            mPushMsgReceiverHandle.showNotification(arrayList.get(0).sessionModel.getSessionId() + "", 1, from_cust_name, content,
                    arrayList.get(0), 0, 0);
        }
    }

}